package cz.spock.core.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cz.spock.core.service.UserService;
import cz.spock.exception.DatabaseException;
import cz.spock.exception.InvalidDataException;
import cz.spock.exception.InvalidInputException;

//@Controller
@Deprecated // because not covered by current architecture
public class UserController extends BaseController {
    
    @Autowired
    private UserService userService;
    
    /**
     * URL: /ajax/account
     * Method: POST
     * 
     * Ajax service for creating new account (and related AccountSecurity)
     * 
     * Params:
     * - login - string, not null
     * - password - string, not null
     * - email - string, not null, must be valid email address
     * - roles - string - possible delimeters [,] [;] [SPACE], default value is ROLE_USER
     * 
     * Error messages:
     * - 41x invalid input data
     * - 500 internal error
     * - 42x data problem - email is already used
     * 
     * Status: not tested
     * 
     * @param request
     * @param response
     */
    @RequestMapping(value = "/ajax/user", method = RequestMethod.POST)
    public void createUser(HttpServletRequest request, HttpServletResponse response) {
        // login and password and email
        String name = this.readParamAsString(request, "name");;
        String surname = this.readParamAsString(request, "surname");
        String birthday = this.readParamAsString(request, "birth");
        String gender = this.readParamAsString(request, "gender");

        // calls service
        try {
            userService.createPerson(name, surname, birthday, gender);
        } catch(InvalidInputException e) {
            sendJson(response, userService.errorToJson(e.getMessage(), e.getErrorCode()));
            return;
        } catch(InvalidDataException e) {
            sendJson(response, userService.errorToJson(e.getMessage(), e.getErrorCode()));
            return;
        } catch(DatabaseException e) {
            sendJson(response, userService.errorToJson(e.getMessage(), e.getErrorCode()));
            return;
        } catch(Exception e) {
            log.severe("Exception in RegistrationController method createAccount: " + e.getMessage());
            sendJson(response, userService.errorToJson("Internal error.", 500));
            return;            
        }
        // success message
        log.finest("registration request done");
        sendJson(response, userService.responseToJson(null));
    }
    
    // delete user by id, or login? BOTH
    public void deleteUser() {
        
    }

}
